package com.qdlc.p2p.biz.freemarker.directive;

import java.io.IOException;
import java.io.Writer;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.qdlc.p2p.dal.dao.AccountDao;
import com.qdlc.p2p.dal.dao.UserDao;
import com.qdlc.p2p.dal.dto.Account;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 *新版我的资产展示
 * @author hcb
 *usage: <@accountInfo  id="2" ></@account>
 *@param id 用户主键Id，String类型。
 *@return  返回拼装出来的html字符串
 */
public class AccountInfoDirectiveModel implements TemplateDirectiveModel{
	
	private static Logger logger = Logger.getLogger(AccountInfoDirectiveModel.class);
	
    private static final String ID = "id";
    
    @SuppressWarnings("unused")
	private UserDao userDao;
    private AccountDao accountDao;
    
    public AccountInfoDirectiveModel(UserDao userDao,AccountDao accountDao){
    	this.userDao = userDao;
    	this.accountDao = accountDao;
    }
    
	@SuppressWarnings("rawtypes")
	@Override
	public void execute(Environment environment, Map map,
			TemplateModel[] atemplatemodel,
			TemplateDirectiveBody templatedirectivebody)
			throws TemplateException, IOException {
		
		Iterator it = map.entrySet().iterator();
		String id = "";
        while (it.hasNext()) {
            Map.Entry entry = (Entry) it.next();
            String paramName = entry.getKey().toString();
            TemplateModel paramValue = (TemplateModel) entry.getValue();
            logger.debug("name:"+paramName);
            logger.debug("r:"+paramValue);
            if (paramName.equals(ID)) {
            	id = paramValue.toString();
            }
        }
        String result=html(id);
        Writer out = environment.getOut();
        out.write(result);
	}
	
	
	private String html(String id){
		StringBuffer sb=new StringBuffer();
		if(!id.equals("")){
			Account account = accountDao.findByUserId(Long.parseLong(id));
			double total = account.getUseMoney();
			DecimalFormat df = new DecimalFormat("0.00");//""00.00"小数点后面的0的个数表示小数点的个数
			String sTotal = df.format(total);
			sb.append(sTotal);
		}
		return sb.toString();
	}
	
}
